﻿using BsForApi.Model;
using BsForApi.Model.JDOout;
using HCDV.HCSP;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace BsForApi
{

    public class JDBs
    {
        //        采收信息加载接口，接口编号api_getpick
        //入参：不能为空
        //入参：机构ID（登录接口返回），采收日期（yyyy-MM-dd）
        //返回要素<list>：采收批次号，地块名称，品种名称
        //采收批次说明：基地＋地块＋品种＋采收日期 作为一个采收批次标识。
        //格式为：1_01_01_2018-10-10(基地ID＋地块ID＋品种ID＋采收日期)
        public static ApiOut<List<PickListOut>> GetPickList(ApiIn<PickListInput> input)
        {
            var re = new ApiOut<List<PickListOut>>();
            re.Info = new List<PickListOut>();
            DataTable dt = new DataTable();
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format(@"select 
0 as sks,0 skg,0 sbs,0 bks,0 bkg,0 bbs, csgetpc,采收日期,计划编号,区域,类型,地块,组长,负责人,面积,品种,
sum(`采摘量`) 采摘量,sum(`入库量`) 入库量,单位,sum(`扣数`)扣数,sum(`框数`) 框数,
dataaddtime,dataadduserid,dataaddusername,databranchid,databranchname,datadepid,datadepname,品种ID,作业ID,
任务ID,地块ID,szkgallcout,szbsallcout,szksallcout
from v采收报表 as t  
where  t.databranchid= {0} and 采收日期>='{1} 00:00:00'and 采收日期<='{1} 23:59:59'
GROUP BY csgetpc", input.LoginInfo.UserOrgId, input.Info.PickTime.ToString("yyyy-MM-dd")));
            }
            foreach (DataRow row in dt.Rows)
            {
                re.Info.Add(new PickListOut
                {
                    dkname = row["地块"].ToString(),
                    pickno = row["csgetpc"].ToString(),
                    pjname = row["品种"].ToString(),
                    taskno = row["计划编号"].ToString()
                });
            }
            return re;
        }

        //        发货目标信息加载接口，接口编号api_getcenterorg
        //入参：空
        //返回要素<list>：机构ID，机构名称
        /// <summary>
        /// 发货目标信息加载
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ApiOut<List<OrgInfoOutpunt>> GetCenterOrgList(ApiIn<string> input)
        {
            var re = new ApiOut<List<OrgInfoOutpunt>>();
            re.Info = new List<OrgInfoOutpunt>();
            DataTable dt = new DataTable();
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format(@"SELECT * from mrbranch where BranchID=150"));
            }
            foreach (DataRow row in dt.Rows)
            {
                re.Info.Add(new OrgInfoOutpunt
                {
                    OrgId = row["BranchID"].ToString(),
                    OrgName = row["BranchName"].ToString(),
                });
            }
            return re;
        }

        /// <summary>
        /// 提交发货汇总信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ApiOut<string> PostPickSend(ApiIn<PickSendInput> input, bool NeedReSetOutInfoToCenter = true)
        {
            var outguid = Guid.NewGuid().ToString();
            var re = new ApiOut<string>();
            using (dbsimple db = new dbsimple())
            {
                //取出对应的采收记录（最近15数据 才能操作）
                var 采收信息s = db.Query(string.Format(@"select 
0 as sks,0 skg,0 sbs,0 bks,0 bkg,0 bbs, csgetpc,采收日期,计划编号,区域,类型,地块,组长,负责人,面积,品种,
sum(`采摘量`) 采摘量,sum(`入库量`) 入库量,单位,sum(`扣数`)扣数,sum(`框数`) 框数,
dataaddtime,dataadduserid,dataaddusername,databranchid,databranchname,datadepid,datadepname,品种ID,作业ID,
任务ID,地块ID,szkgallcout,szbsallcout,szksallcout
from v采收报表 as t  
where  t.databranchid= {0} and 采收日期>='{1} 00:00:00' and  csgetpc='{2}'
GROUP BY csgetpc", input.LoginInfo.UserOrgId, DateTime.Now.AddDays(-65).ToString("yyyy-MM-dd"), input.Info.pickno));
                if (采收信息s.Rows.Count == 0) return re;
                var 采收信息 = 采收信息s.Rows[0];
                //----原料处理
                //删除原料的汇总
                db.exe(string.Format("delete from task_send_info where csgetpc='{0}' and setdate='{1}' and settocenterid={2} and productstate='原料'"
                    , input.Info.pickno, input.Info.sendday, input.Info.sendToOrgId));
                //插入原料的汇总
                db.exe(string.Format(@"INSERT INTO task_send_info(sljl,csgetpc,settocenterid,productstate,setdate,slcs,allbs,addtime) 
VALUES ('{0}','{1}','{2}','原料','{3}','{4}','{5}','{6}')", input.Info.ylkg, input.Info.pickno,
                                                                     input.Info.sendToOrgId, input.Info.sendday, input.Info.ylks, input.Info.ylbs,
                                                                     DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                                                     ));
                //删除原料的发货明细
                db.exe(string.Format(@"delete from hsc_task_store_out where dataaddtime='{0} 00:00:00' 
and csgetpc='{1}' and productstate='原料' and inouttype='发往加工中心'", input.Info.sendday, input.Info.pickno));
                //插入原料的发货明细

                db.exe(string.Format(@"INSERT INTO hsc_task_store_out(
datafromdesc,datafromkeyid,csgetpc,outdesc,databranchname,inoutstorestate,storefortype1,carid,productstate,outstate,
taskid,dkid,storeall,outgid,dkname,
dataaddusername,storehouseid,
dataaddtime,taskworktime,
taskfromorgname,storeksall,productname,productid,
inouttype,jjusername,datadepid,dataadduserid,datadepname,
taskno,taskfromorgid,hasoutall,carinfo,databranchid,tasklistid,datafromtable)
VALUES ('出库','{0}','{1}','{2}','{3}','待入库','{4}','{5}','原料','运输中',
'{6}','{7}','{8}','{9}','{10}',
'{11}','0',
'{12}','{13}',
'{14}','{15}','{16}','{17}',
'{18}','{19}','{20}','{21}','{22}',
'{23}','{24}','{25}','{26}','{27}','{28}','hsc_task_info')"
                , 采收信息["作业ID"].ToString(),
                input.Info.pickno,
                input.Info.outdesc,
                input.OrgName,
                input.Info.ylbs,
                input.Info.carId,
                采收信息["任务ID"].ToString(),
                采收信息["地块ID"].ToString(),
                input.Info.ylkg,
                outguid,
                采收信息["地块"].ToString(),
                input.LoginInfo.UserName, //{11}
                input.Info.sendday,
                采收信息["采收日期"].ToString(),//{13}
                采收信息["databranchname"].ToString(),
                input.Info.ylks,
                采收信息["品种"].ToString(),
                采收信息["品种ID"].ToString(),//{17}
                "发往加工中心",
                "",
                采收信息["datadepid"].ToString(),
                input.LoginInfo.UserId,
                "",//{22}
                采收信息["计划编号"].ToString(),
                采收信息["databranchid"].ToString(),
                "0",
                input.Info.carInfo,
                采收信息["databranchid"].ToString(),
                采收信息["作业ID"].ToString()
                ));



                //----包装处理
                //删除原料的汇总
                db.exe(string.Format("delete from task_send_info where csgetpc='{0}' and setdate='{1}' and settocenterid={2} and productstate='包装品'"
                    , input.Info.pickno, input.Info.sendday, input.Info.sendToOrgId));
                //插入的汇总
                db.exe(string.Format(@"INSERT INTO task_send_info(sljl,csgetpc,settocenterid,productstate,setdate,slcs,allbs) 
VALUES ('{0}','{1}','{2}','包装品','{3}','{4}','{5}')", input.Info.cpkg, input.Info.pickno,
                                                                     input.Info.sendToOrgId, input.Info.sendday, input.Info.cpks, input.Info.cpbs
                                                                     ));
                //删除的发货明细
                db.exe(string.Format(@"delete from hsc_task_store_out where dataaddtime='{0} 00:00:00' 
and csgetpc='{1}' and productstate='包装品' and inouttype='发往加工中心'", input.Info.sendday, input.Info.pickno));
                //插入的发货明细

                db.exe(string.Format(@"INSERT INTO hsc_task_store_out(
datafromdesc,datafromkeyid,csgetpc,outdesc,databranchname,inoutstorestate,storefortype1,carid,productstate,outstate,
taskid,dkid,storeall,outgid,dkname,
dataaddusername,storehouseid,
dataaddtime,taskworktime,
taskfromorgname,storeksall,productname,productid,
inouttype,jjusername,datadepid,dataadduserid,datadepname,
taskno,taskfromorgid,hasoutall,carinfo,databranchid,tasklistid,datafromtable)
VALUES ('出库','{0}','{1}','{2}','{3}','待入库','{4}','{5}','包装品','运输中',
'{6}','{7}','{8}','{9}','{10}',
'{11}','0',
'{12}','{13}',
'{14}','{15}','{16}','{17}',
'{18}','{19}','{20}','{21}','{22}',
'{23}','{24}','{25}','{26}','{27}','{28}','hsc_task_info')"
               , 采收信息["作业ID"].ToString(),
               input.Info.pickno,
               input.Info.outdesc,
               input.OrgName,
               input.Info.cpbs,
               input.Info.carId,
               采收信息["任务ID"].ToString(),
               采收信息["地块ID"].ToString(),
               input.Info.cpkg,
               outguid,
               采收信息["地块"].ToString(),
               input.LoginInfo.UserName, //{11}
               input.Info.sendday,
               采收信息["采收日期"].ToString(),//{13}
               采收信息["databranchname"].ToString(),
               input.Info.cpks,
               采收信息["品种"].ToString(),
               采收信息["品种ID"].ToString(),//{17}
               "发往加工中心",
               "",
               采收信息["datadepid"].ToString(),
               input.LoginInfo.UserId,
               "",//{22}
               采收信息["计划编号"].ToString(),
               采收信息["databranchid"].ToString(),
               "0",
               input.Info.carInfo,
               采收信息["databranchid"].ToString(),
               采收信息["作业ID"].ToString()
               ));

            }
            if (NeedReSetOutInfoToCenter) GetReSetOutInfoToCenter(input.LoginInfo.UserOrgId, input.Info.sendday);

            BsForApi.JDOutStore.原料直接登记发货时同步基地的原料出库(input.Info.pickno, input.Info.ylkg);

            BsForApi.JDOutStore.成品直接登记发货时同步基地的原料出库(input.Info.pickno, input.Info.cpkg);

            return re;
        }
        /// <summary>
        /// 更新发货的汇总
        /// </summary>
        /// <param name="databranchid"></param>
        /// <param name="day"></param>
        /// <param name="ismanage"></param>
        /// <returns></returns>
        public static string GetReSetOutInfoToCenter(string databranchid, string day = null, bool ismanage = false)
        {
            if (day == null)
                day = DateTime.Now.ToString("yyyy-MM-dd");
            string sql = @"insert into hsc_task_store_out_group
(
select id,outgid,inouttype,outdesc,taskid,taskno,tasklistid,taskworktime,taskfromorgid,taskfromorgname,dkname,dkid,storehouseid,
productid,productgid,productname,SUM(storeall) storeall,SUM(storefortype1) as storefortype1,SUM(storefortype2) as storefortype2,SUM(storefortype3) as storefortype3,
storealluseall,price,hasoutall,unit,jgcount,owneruserid,lockcout,outstate,jjuserid,jjusername,productstate,'待质检',dataadduserid,datadepid,databranchid,
datadepname,databranchname,dataaddusername,datafromtable,datafromkeyid,datafromdesc,endtime,
date_format(dataaddtime,'%Y-%m-%d 00:00:00') as dataaddtime ,
storefortype1out,storefortype2out,storefortype3out,storefortype4out,storefortype5out,moneycount,
SUM(storefortype4) storefortype4,
SUM(storefortype5) storefortype5,carid,carinfo,0,sum(storeksall) storeksall,csgetpc,'否'
from hsc_task_store_out
 where    
dataaddtime>='{1} 00:00:00' and dataaddtime<'{1} 23:59:59'  and taskfromorgid ={0} and 
 inoutstorestate in('待入库','入库中') and inouttype in('发往加工中心','发货记录登记')   
GROUP BY taskid,taskfromorgid,productid,date_format(dataaddtime,'%Y-%m-%d 00:00:00'),productstate,csgetpc
)";
            sql = string.Format(sql, databranchid, day);
            try
            {
                using (dbsimple db = new dbsimple())
                {
                    //先删除
                    db.SpExe(string.Format("DELETE from    hsc_task_store_out_group where taskfromorgid={0} and dataaddtime='{1} 00:00:00' and inoutstorestate='待质检'", databranchid, day));
                    //再插入
                    db.SpExe(sql);
                    //


                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "处理成功";

        }


        //      入参：不能为空
        //入参：采收批次号（采收信息下拉），发货日期（yyyy-MM-dd），发货目标（机构 ID）
        //返回要素<list>：类型（原料／包装品），框数，重量，包数
        //这里会返回０～２行数据 （类型分开返回）
        /// <summary>
        /// 发货汇总信息加载接口，接口编号api_getpicksend
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ApiOut<List<GetPickSendOut>> GetPickSend(ApiIn<GetPickSendInput> input)
        {
            var re = new ApiOut<List<GetPickSendOut>>();
            re.Info = new List<GetPickSendOut>();
            DataTable dt = new DataTable();
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format(@"SELECT  *,0 as rowhcindex FROM task_send_info where 1=1 
and csgetpc = '{0}' 
and setdate = '{1} 00:00:00'  and  settocenterid={2}
order by csgetpc", input.Info.pickno, input.Info.sendday, input.Info.sendToOrgId));
            }
            foreach (DataRow row in dt.Rows)
            {
                re.Info.Add(new GetPickSendOut
                {
                    id = row["id"].ToString(),
                    allbs = double.Parse(row["allbs"].ToString()),
                    csgetpc = row["csgetpc"].ToString(),
                    productstate = row["productstate"].ToString(),
                    setdate = row["setdate"].ToString(),
                    settocenterid = row["settocenterid"].ToString(),
                    slcs = double.Parse(row["slcs"].ToString()),
                    sljl = double.Parse(row["sljl"].ToString()),
                });
            }
            return re;
        }


        //        提交发货码信息接口，接口编号api_postpicksendcode
        //入参：不能为空
        //入参：发货码，所有当前界面控件数据(1~6)
        //１采收日期
        //２采收信息
        //３发货日期
        //４发货目标
        //下拉（固定数据：原料／包装品） 及序号
        //返回：状态
        /// <summary>
        /// 提交发货码信息接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ApiOut<string> PostPickSendCode(ApiIn<PickSendCodeInput> input)
        {
            var outguid = Guid.NewGuid().ToString();
            var re = new ApiOut<string>();
            using (dbsimple db = new dbsimple())
            {
                db.exe(string.Format(@"update   task_send_info_list  set isdel =1 where codepc='{0}'", input.Info.codepc));
                var id = db.SpExeBackid(string.Format(@"INSERT INTO task_send_info_list
(getdata,csgetpc,settocenterid,productstate,setdate,databranchid,codeinfo,codepc,codeindex,isdel) 
VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}',0)",
                   input.Info.getdata,
                     input.Info.csgetpc,
                     input.Info.settocenterid,
                     input.Info.productstate,
                     input.Info.setdate, input.Info.databranchid, input.Info.codeinfo, input.Info.codepc, input.Info.codeindex
                   ));
                re.Info = id.ToString();

            }
            return re;
        }


        //      入参：采收日期（＊），当前机构（＊），采收批次号（界面控件数据，有则传），发货日期（＊），发货目标（＊）
        //返回要素<list>：发货码，发货码说明
        /// <summary>
        /// 加载发货码明细，接口编号api_getpicksendcode
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static ApiOut<List<PickSendCodeOutput>> GetPickSendCode(ApiIn<PickSendCodeInput> input)
        {
            var re = new ApiOut<List<PickSendCodeOutput>>();
            re.Info = new List<PickSendCodeOutput>();
            string where = "";
            if (!string.IsNullOrEmpty(input.Info.databranchid))
            {
                where += " and a.databranchid=" + input.Info.databranchid;
            }
            if (!string.IsNullOrEmpty(input.Info.getdata))
            {
                where += " and a.getdata='" + input.Info.getdata + "'";
            }
            if (!string.IsNullOrEmpty(input.Info.csgetpc))
            {
                where += " and a.csgetpc='" + input.Info.csgetpc + "'";
            }
            if (!string.IsNullOrEmpty(input.Info.setdate))
            {
                where += " and a.setdate='" + input.Info.setdate + "'";
            }
            if (!string.IsNullOrEmpty(input.Info.codepc))
            {
                where += " and a.codepc='" + input.Info.codepc + "'";
            }
            if (input.Info.settocenterid > 0)
            {
                where += " and a.settocenterid='" + input.Info.settocenterid + "'";
            }

            DataTable dt = new DataTable();
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format(@"select a.*,b.slcs,b.sljl from task_send_info_list a INNER JOIN task_send_info b on 
a.csgetpc=b.csgetpc and a.productstate=b.productstate and a.setdate=b.setdate and a.settocenterid=b.settocenterid where 1=1 " + where));
            }
            foreach (DataRow row in dt.Rows)
            {
                re.Info.Add(new PickSendCodeOutput
                {
                    codeindex = int.Parse(row["codeindex"].ToString()),
                    codeinfo = row["codeinfo"].ToString(),
                    codepc = row["codepc"].ToString(),
                    csgetpc = row["csgetpc"].ToString(),
                    databranchid = row["databranchid"].ToString(),
                    getdata = row["getdata"].ToString(),
                    productstate = row["productstate"].ToString(),
                    setdate = row["setdate"].ToString(),
                    settocenterid = long.Parse(row["settocenterid"].ToString()),
                    slcs = int.Parse(row["slcs"].ToString()),
                    sljl = int.Parse(row["sljl"].ToString()),
                });
            }
            return re;
        }

        /// <summary>
        /// 删除发货码
        /// </summary>
        /// <param name="input">Info：对应为发货码</param>
        /// <returns></returns>
        public static ApiOut<string> DelPickSendCode(ApiIn<string> input)
        {
            var outguid = Guid.NewGuid().ToString();
            var re = new ApiOut<string>();
            using (dbsimple db = new dbsimple())
            {
                db.exe(string.Format(@"delete from task_send_info_list where codepc='{0}'", input.Info));

            }
            return re;
        }

        /// <summary>
        /// 根据发货码 获取待入库信息
        /// </summary>
        /// <param name="input">Info为发货码</param>
        /// <returns></returns>
        public static ApiOut<List<CenterAwaitInStoreInfo>> GetSendInfoByCode(ApiIn<string> input)
        {
            var re = new ApiOut<List<CenterAwaitInStoreInfo>>();
            re.Info = new List<CenterAwaitInStoreInfo>();
            double id = 0;
            double.TryParse(input.Info, out id);
            DataTable dt = new DataTable();
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(string.Format(@"SELECT  a.codepc,a.codeinfo,a.id codeid,b.slcs,b.sljl ,b.id senndallid, t.csgetpc,storeksall,moneycount,0 price,
storefortype1,storefortype2,storefortype3,storefortype1out,storefortype2out,storefortype3out,storefortype1-storefortype1out 
as storefortype1needout ,storefortype2-storefortype2out as storefortype2needout,storefortype3-storefortype3out as storefortype3needout,
CONCAT('needtodo',t.id) as needtodoid,CONCAT('kl',t.id) as klid,CONCAT('needtoin',t.id) as needtoinid,kl,storeall-hasoutall as needtoin,t.id,
inoutstorestate,taskfromorgid,taskfromorgname,taskid,taskno,tasklistid,productname,dkid,dkname,dataaddtime,storeall,storeall-hasoutall
 as needtoout,lockcout,hasoutall,outstate,taskworktime,t.productstate,0 as
 rowhcindex FROM hsc_task_store_out_group t 
left join task_send_info_list a  on t.csgetpc= a.csgetpc and t.dataaddtime=a.setdate and t.productstate=a.productstate
left JOIN task_send_info b on  
t.csgetpc=b.csgetpc and t.productstate=b.productstate and t.dataaddtime=b.setdate and 150=b.settocenterid
  where 1=1 and (a.codepc='{0}' or a.id={1})", input.Info, id));
            }
            foreach (DataRow row in dt.Rows)
            {
                re.Info.Add(new CenterAwaitInStoreInfo
                {
                    codepc = row["codepc"].ToString(),
                    codeinfo = row["codeinfo"].ToString(),
                    codeid = row["codeid"].ToString(),
                    slcs = row["slcs"].ToString(),
                    sljl = row["sljl"].ToString(),
                    csgetpc = row["csgetpc"].ToString(),
                    productname = row["productname"].ToString(),
                    inoutstorestate = row["inoutstorestate"].ToString(),
                    outstate = row["outstate"].ToString(),
                    productstate = row["productstate"].ToString(),
                });
            }
            return re;
        }



        //2018-10-14 11:03:40,095 [12940] INFO  loginfo [(null)] - 执行sql spExe:UPDATE hsc_task_store_out_group set hasoutall=(hasoutall+1),storefortype1out=(storefortype1out+1),storefortype2out=(storefortype2out+0),storefortype3out=(storefortype3out+0),inoutstorestate='入库中' where id='18288'

        //2018-10-14 11:03:40,141 [13988] INFO  loginfo [(null)] - 执行sql query:select taskid,taskfromorgid,productid,dataaddtime,productstate  from hsc_task_store_out_group where id= 18288

        //2018-10-14 11:03:40,143 [13988] INFO  loginfo [(null)] - 执行sql spExe:update hsc_task_store_out set centerintime='2018-10-14 00:00:00',
        //centeringuid='e46518fc-c955-fb9a-16fd-6dae26e857e3',inoutstorestate='已入库'
        //where dataaddtime='2018/10/13 0:00:00' 
        //and inoutstorestate in('待入库','入库中') 
        //and taskfromorgid=149
        //and taskid=613 
        /// <summary>
        /// 根据发货码 获取待入库信息
        /// </summary>
        /// <param name="input">Info为发货码</param>
        /// <returns></returns>
        public static ApiOut<string> CenterInStoreByCodeInfo(ApiIn<CenterInStoreInfo> input)
        {
            var re = new ApiOut<string>();
            var outguid = Guid.NewGuid().ToString();
            DataRow sendInfo;
            using (dbsimple db = new dbsimple())
            {
                //取出对应的发货明细信息
                var dt = db.Query(string.Format(@"SELECT t.productid, a.codepc,a.codeinfo,a.id codeid,b.slcs,b.sljl ,b.id senndallid, t.csgetpc,storeksall,moneycount,0 price,
storefortype1,storefortype2,storefortype3,storefortype1out,storefortype2out,storefortype3out,storefortype1-storefortype1out 
as storefortype1needout ,storefortype2-storefortype2out as storefortype2needout,storefortype3-storefortype3out as storefortype3needout,
CONCAT('needtodo',t.id) as needtodoid,CONCAT('kl',t.id) as klid,CONCAT('needtoin',t.id) as needtoinid,kl,storeall-hasoutall as needtoin,t.id,
inoutstorestate,taskfromorgid,taskfromorgname,taskid,taskno,tasklistid,productname,dkid,dkname,dataaddtime,storeall,storeall-hasoutall
 as needtoout,lockcout,hasoutall,outstate,taskworktime,t.productstate,0 as
 rowhcindex FROM hsc_task_store_out_group t 
left join task_send_info_list a  on t.csgetpc= a.csgetpc and t.dataaddtime=a.setdate and t.productstate=a.productstate
left JOIN task_send_info b on  
t.csgetpc=b.csgetpc and t.productstate=b.productstate and t.dataaddtime=b.setdate and 150=b.settocenterid
  where 1=1 and a.codepc='{0}'", input.Info.codepc));
                if (dt.Rows.Count == 0)
                {
                    re.SetError("发货码不存在，或者数据异常");
                    return re;
                }

                sendInfo = dt.Rows[0];
                //删除之前的记录
                db.exe(string.Format(@"delete from hsc_task_store_process where
csgetpc='{0}' 
and dataaddtime='{1}' 
and productstate='{2}' and databranchid={3}",
                    sendInfo["csgetpc"].ToString(),
                    input.Info.dataaddtime,
                    sendInfo["productstate"].ToString(),
                    input.LoginInfo.UserOrgId
                    ));
                //分析包数  --取出配置
                double bs = 1;
                DataTable dtproduct = db.Query("select nv1,nv2  from yw_baseinfo  where id=" + sendInfo["productid"].ToString());
                if (dtproduct.Rows.Count > 0)
                {
                    if (sendInfo["productstate"].ToString() == "原料")
                    {
                        if (!string.IsNullOrEmpty(dtproduct.Rows[0]["nv1"].ToString()))
                        {
                            bs = int.Parse(dtproduct.Rows[0]["nv1"].ToString()) * input.Info.storeall;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(dtproduct.Rows[0]["nv2"].ToString()))
                        {
                            bs = int.Parse(dtproduct.Rows[0]["nv2"].ToString()) * input.Info.storeall;
                        }
                    }
                }


                db.exe(string.Format(@"INSERT INTO hsc_task_store_process(datafromkeyid,codecount,csgetpc,outdesc,databranchname,
inoutstorestate,storefortype1,productstate,taskid,dkid,
storeall,storefortype3,storeallok,kl,dkname,
dataaddusername,storehouseid,dataaddtime,inouttype,outstate,
taskfromorgname,storeksall,productname,productid,moneycount,
jjusername,datadepid,datadepname,taskno,storefortype2,
taskfromorgid,hasoutall,dataadduserid,databranchid,price,
tasklistid,taskworktime,jjuserid,outgid,datafromtable)  
        VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17} 00:00:00','{18}','{19}',
'{20}','{21}','{22}','{23}','{24}',
'{25}','{26}','{27}','{28}','{29}','{30}','{31}','{32}','{33}','{34}','{35}','{36}','{37}','{38}','{39}')",
                   sendInfo["id"].ToString(), ((int)bs).ToString(), sendInfo["csgetpc"].ToString(), input.Info.outdesc, input.OrgName,
                "待出库处理", sendInfo["storefortype1"].ToString(), sendInfo["productstate"].ToString(), sendInfo["taskid"].ToString(), sendInfo["dkid"].ToString(),
                input.Info.storeall, sendInfo["storefortype3"].ToString(), sendInfo["storeall"].ToString(), "0", sendInfo["dkname"].ToString(),
                input.LoginInfo.UserName, "0", input.Info.dataaddtime, "运输入库", "待出库处理",
                 sendInfo["taskfromorgname"].ToString(), input.Info.storeksall, sendInfo["productname"].ToString(), sendInfo["productid"].ToString(), "0",
 input.Info.jjusername, input.LoginInfo.UserDepId, input.LoginInfo.UserDepName, sendInfo["taskno"].ToString(), sendInfo["storefortype2"].ToString(),
   sendInfo["taskfromorgid"].ToString(), 0, input.LoginInfo.UserId, input.LoginInfo.UserOrgId, sendInfo["price"].ToString(),
   sendInfo["tasklistid"].ToString(), sendInfo["taskworktime"].ToString(), input.Info.jjuserid, outguid, "hsc_task_store_out_group"
                ));
                db.exe(string.Format(@"UPDATE task_send_info_list set
codestate='已入库' where id={0}", sendInfo["codeid"].ToString()));

                db.exe(string.Format(@"UPDATE hsc_task_store_out_group set
hasoutall=(hasoutall+{1}),
storefortype1out=(storefortype1out+{2}),
storefortype2out=(storefortype2out+0),
storefortype3out=(storefortype3out+0),
inoutstorestate='入库中' where id={0}", sendInfo["id"].ToString(), input.Info.storeall, sendInfo["storefortype1"].ToString()));

                GetUpdateCenterInTimeToBaseOut(sendInfo["id"].ToString(), outguid, input.Info.dataaddtime);
            }
            return re;

        }

        /// <summary>
        /// 任务-更新中心的入库时间到基地的发货记录表中
        /// </summary>
        /// <returns></returns>
        private static string GetUpdateCenterInTimeToBaseOut(string id, string inguid = "", string intime = "")
        {

            try
            {
                if (string.IsNullOrEmpty(intime)) intime = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                using (dbsimple db = new dbsimple())
                {
                    //取出本次的处理信息的关键信息
                    var doinfo = db.Query("select taskid,taskfromorgid,productid,dataaddtime,productstate  from hsc_task_store_out_group where id= " + id);
                    //根据关键信息取出对应的基地发货记录,更新时间
                    db.SpExe(string.Format(@"update hsc_task_store_out set centerintime='{4}',
centeringuid='{0}',inoutstorestate='已入库'
where dataaddtime='{1}' 
and inoutstorestate in('待入库','入库中') 
and taskfromorgid={2}
and taskid={3} ",
                        inguid,
                        doinfo.Rows[0]["dataaddtime"].ToString(),
                        doinfo.Rows[0]["taskfromorgid"].ToString(),
                         doinfo.Rows[0]["taskid"].ToString(), intime
                        ));

                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "处理成功";

        }
    }
}
